package com.runa.monitor.platinterface.netservice.handler;

import com.runa.monitor.platinterface.base.BaseContainer;
import com.runa.monitor.platinterface.netservice.connect.Session;
import com.runa.monitor.platinterface.netservice.server.ConnectorServer;
import com.runa.monitor.platinterface.netservice.server.Server;
import com.runa.protocol.dto.IResponseData;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author zhuj
 */
@ChannelHandler.Sharable
public class ResponseHandler extends SimpleChannelInboundHandler<IResponseData> {

    private static final Logger logger = LoggerFactory.getLogger(ResponseHandler.class);

    private Server server;

    ResponseHandler(Server server) {
        this.server = server;
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, IResponseData msg) {
        Session session = BaseContainer.getSession(ctx.channel().id().asLongText());
        if (session != null) {
            session.receiving(msg);
        }
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        super.channelActive(ctx);
        if (server instanceof ConnectorServer) {
            ConnectorServer cServer = (ConnectorServer) server;
            cServer.connected();
        }
        logger.info("server: {} online !", ctx.channel().remoteAddress());
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) {
        Channel channel = ctx.channel();
        logger.info("server: {} offline!", ctx.channel().remoteAddress());
        Session session = BaseContainer.getSession(channel.id().asLongText());
        if (session != null) {
            BaseContainer.removeSession(channel.id().asLongText());
            session.setOnlineStatus(false);
            server.reConnect(session);
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        logger.error("Error: ",cause);
    }
}
